<template>
    <div style="display: flex; justify-content: center; background-color: #fff;">
        <div style="width: 755px">
            <div>我的购物车</div>
            <div style="padding: 20px;">
                <el-button type="primary" style="float: right" @click="forSubmitOrder" >提交订单</el-button>
            </div>
            <div style="display: flex; justify-content: center; margin-top: 20px;">
                <el-table :data="car" stripe style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"/>
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="serial" label="产品编号" width="100" />
                    <el-table-column prop="title" label="名称" width="200" show-overflow-tooltip />
                    <el-table-column prop="count" label="数量" width="180" />
                    <el-table-column prop="total" label="总价" />
                    <el-table-column label="操作">
                        <template v-slot:default="scope">
                            <el-button type="danger" :icon="Delete" circle @click="deleteCar(scope.row.id)" />
                            <el-button :icon="Search" circle @click="() => router.push({path: '/detail', query: {'id': scope.row.id}})" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { Delete,Search} from '@element-plus/icons-vue'
import { getCarOrder,delCarOrder, submitOrder } from '@/requests';
import { ElMessage } from 'element-plus';
const router = useRouter();
const car = ref();
const selectionRow = ref();

const forCarOrder = async() =>{
    const res = await getCarOrder();
    if (res.status === 2000){
        car.value = res.data;
    }else{
        console.log("获取列表失败")
    }
}

forCarOrder();

const deleteCar = async(id)=>{
    const res = await delCarOrder({"id": id})
    if (res.status === 2000){
        ElMessage.success("删除成功")
    }else{
        ElMessage.error("删除失败")
    };
    forCarOrder();
};

// 获取选择的行
const handleSelectionChange = (selection)=>{
    selectionRow.value = selection.map(row => row.id);
    console.log(selectionRow.value)
}

// 提交订单
const forSubmitOrder = async()=>{
    console.log(selectionRow)
    const res = await submitOrder({"ids": JSON.stringify(selectionRow.value)});
    if (res.status === 2000){
        ElMessage.success("提交订单成功");
        router.push({path: "/shopCenter"})
    }else{
        if(res.status === 4000){
            ElMessage.error(res.msg);
            router.push({path: '/user'})
        }else{
            ElMessage.error("提交订单失败");
        }
        
    }
}
</script>

<style scoped></style>